<template>
  <div class="app-container">
    <!-- 搜索 -->
    <template>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="等级名称" prop="levelTitle">
          <el-input
            v-model="queryParams.levelTitle"
            placeholder="请输入等级名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="店铺ID" prop="shopId" v-if="$store.getters && $store.getters.admin">
          <el-input
            v-model="queryParams.shopId"
            placeholder="请输入店铺ID"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </template>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['market:level:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="levelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="55" align="center" />
      <!-- <el-table-column label="等级编号" prop="levelId" width="120" /> -->
      <el-table-column label="等级名称" prop="levelTitle" min-width="90" />
      <el-table-column label="等级图标" align="center" key="levelImage" min-width="120" >
        <template slot-scope="scope">
          <div class="flex-center">
            <el-image size="medium" fit="fill" style="width: 60px; height: 30px" :src="scope.row.levelImage" alt="404"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="首单提成(%)" prop="firstOrderCommissionRate" min-width="100" />
      <el-table-column label="续单提成(%)" prop="continueOrderCommissionRate" min-width="100" />
      <el-table-column label="首赏提成(%)" prop="firstRewardCommissionRate" min-width="100" />
      <el-table-column label="续赏提成(%)" prop="continueRewardCommissionRate" min-width="100" />
      <el-table-column label="PK胜方提成(%)" prop="pkVictoryCommissionRate" min-width="120" />
      <el-table-column label="PK败方提成(%)" prop="pkDefeatCommissionRate" min-width="120" />
      <el-table-column label="PK提成门槛(元)" prop="pkCommissionAmount" min-width="120" />
      <el-table-column label="达级需月收益(元)" prop="advanceAmount" min-width="120" />
      <el-table-column label="排序" prop="levelSort" min-width="70" sortable="custom" :sort-orders="['descending', 'ascending']" />
      <el-table-column label="店铺名称" prop="shopInfo.shopName" min-width="120" v-if="$store.getters && $store.getters.admin" />
      <el-table-column label="操作" align="center" fixed="right" min-width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['market:level:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['market:level:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-row :gutter="20">
      <el-col :sm="24" :lg="24">
        <blockquote class="text-warning" style="font-size: 14px">
          <h4 :class="v.type" v-for="(v, i) in tips">{{i + 1 }}、{{ v.title }}</h4>
        </blockquote>
      </el-col>
    </el-row>

    <!-- 添加或修改等级配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="等级名称" prop="levelTitle">
              <el-input v-model="form.levelTitle" placeholder="请输入等级名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="levelSort">
              <el-input v-model="form.levelSort" placeholder="请输入排序" type="number" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="等级图标" prop="levelImage">
              <el-input v-model="form.levelImage" placeholder="图片地址" class="mgb10" v-if="$store.getters && $store.getters.admin"/>
              <ImageUpload v-model="form.levelImage" :file-size="2" :file-type="['png', 'jpg', 'jpeg', 'gif']" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="首单提成比例" prop="firstOrderCommissionRate">
              <el-input v-model="form.firstOrderCommissionRate" placeholder="请输入首单提成比例" type="number" maxlength="1">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="续单提成比例" prop="continueOrderCommissionRate">
              <el-input v-model="form.continueOrderCommissionRate" placeholder="请输入续单提成比例" type="number" maxlength="50" >
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="首次打赏提成比例" prop="firstRewardCommissionRate">
              <el-input v-model="form.firstRewardCommissionRate" placeholder="请输入首次打赏提成比例" type="number" maxlength="50">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="续打赏提成比例" prop="continueRewardCommissionRate">
              <el-input v-model="form.continueRewardCommissionRate" placeholder="请输入续打赏提成比例" type="number" maxlength="50">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="PK胜方提成比例" prop="pkVictoryCommissionRate">
              <el-input v-model="form.pkVictoryCommissionRate" placeholder="请输入PK胜方提成比例" type="number" maxlength="50" >
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="PK败方提成比例" prop="pkDefeatCommissionRate">
              <el-input v-model="form.pkDefeatCommissionRate" placeholder="请输入PK败方提成比例" type="number" maxlength="50">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="PK提成门槛(元)" prop="pkCommissionAmount">
              <el-input v-model="form.pkCommissionAmount" placeholder="请输入PK提成门槛" type="number" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="达级需月收益(元)" prop="advanceAmount">
              <el-input v-model="form.advanceAmount" placeholder="请输入PK提成门槛" type="number" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLevel, getLevel, delLevel, addLevel, updateLevel } from "@/api/market/level";
const validateAcquaintance = (rule, value, callback) => {
  // 输入 8--，value 为 8
  // 估计这里内部使用了 parseInt() / parseFloat()
  if (value < 0 || value > 100) {
    callback(new Error('数字在在 0 至 100之间'))
  } else {
    callback()
  }
}
const validateAmount = (rule, value, callback) => {
  if (!value) {
    return callback();
  }
  if (!/^(\d+|\d+.\d{1,2})$/.test(value)) {
    callback(new Error('请输入正确的金额格式'));
  } else {
    callback();
  }
}
export default {
  name: "Level",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 等级表格数据
      levelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        levelTitle: undefined,
        shopId: undefined,
        orderByColumn: 'levelSort',
        isAsc: 'ascending',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        levelTitle: [
          { required: true, message: "等级名称不能为空", trigger: "blur" }
        ],
        levelImage: [
          { required: true, message: "等级图标不能为空", trigger: "blur" }
        ],
        levelSort: [
          { required: true, message: "等级顺序不能为空", trigger: "blur" }
        ],
        firstOrderCommissionRate: [
          { required: true, trigger: "blur", message: "请输入续单提成比例(%)" },
          { validator: validateAcquaintance, trigger: 'blur' }
        ],
        continueOrderCommissionRate: [
          { required: true, trigger: "blur", message: "请输入续单提成比例(%)" },
          { validator: validateAcquaintance, trigger: 'blur' }
        ],
        firstRewardCommissionRate: [
          { required: true, trigger: "blur", message: "请输入首次打赏提成比例(%)" },
          { validator: validateAcquaintance, trigger: 'blur' }
        ],
        continueRewardCommissionRate: [
          { required: true, trigger: "blur", message: "请输入续打赏提成比例(%)" },
          { validator: validateAcquaintance, trigger: 'blur' }
        ],
        pkVictoryCommissionRate: [
          { required: true, trigger: "blur", message: "请输入PK胜方提成比例(%)" },
          { validator: validateAcquaintance, trigger: 'blur' }
        ],
        pkDefeatCommissionRate: [
          { required: true, trigger: "blur", message: "请输入PK败方提成比例(%)" },
          { validator: validateAcquaintance, trigger: 'blur' }
        ],
        pkCommissionAmount: [
          { required: true, trigger: "blur", message: "请输入PK提成门槛" },
          { validator: validateAmount, trigger: 'blur' }
        ],
        advanceAmount: [
          { required: true, trigger: "blur", message: "达级需月收益" },
          { validator: validateAmount, trigger: 'blur' }
        ],
      },
      tips: [
        { title: 'PK提成门槛：PK双方店员的金额在结束结算时，都分别达到其等级的门槛金额，该PK才是有效PK，否则为无效PK，无效PK不会进行结算，PK时间内获得收益最高的为胜方，收益相等或者最低的为败方', type: 'text-muted'},
        { title: '有效PK举例：高等级店员（假设门槛金额：1000元）和低等级店员的PK（假设门槛金额：10元），PK结束时，高等级的收入为1001元，低等级的PK收入11元，此PK属于有效PK，以此类推', type: 'text-muted'},
        { title: '无效PK举例：高等级店员（假设门槛金额：1000元）和低等级店员的PK（假设门槛金额：10元），PK结束时，高等级的收入为1001元，低等级的PK收入9元，此PK属于无效PK，以此类推', type: 'text-muted'},
        { title: '有效PK的提成：按照所在等级的胜方和败方提成比例，分别进行结算', type: 'text-muted'},
        { title: '结算方式：PK提成、接单提成、打赏提成三者独立结算，比如店员参与PK，接单提成、打赏提成和PK（有效PK）提成店员都能获得，提成的基数为客户下单金额', type: 'text-muted'},
        { title: '达级需月收益：统计店员最近7天内，接单及打赏的总收益如果达到该金额，则自动晋级该等级，若所有等级的金额全部达到，则取最高金额的等级，每天凌晨统计一次', type: 'text-danger'},
        { title: '降级处理：未能保持达级需月收益则降到对应等级，请在店铺设置中开启，系统默认不进行降级', type: 'text-muted'},
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询等级列表 */
    getList() {
      this.loading = true;
      listLevel(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.levelList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        levelId: undefined,
        levelTitle: undefined,
        levelImage: undefined,
        firstOrderCommissionRate: undefined,
        continueOrderCommissionRate: undefined,
        firstRewardCommissionRate: undefined,
        continueRewardCommissionRate: undefined,
        pkVictoryCommissionRate: undefined,
        pkDefeatCommissionRate: undefined,
        pkCommissionAmount: undefined,
        advanceAmount: undefined,
        levelSort: 0,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.levelId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加等级";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      console.log(row)
      const levelId = row.levelId || this.ids
      getLevel(levelId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改等级";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.levelId != undefined) {
            updateLevel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLevel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const levelIds = row.levelId || this.ids;
      this.$modal.confirm('是否确认删除等级编号为"' + levelIds + '"的数据项？').then(function() {
        return delLevel(levelIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>